package com.prs.core.workflow.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.activiti.engine.ProcessEngine;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.IdentityLink;
import org.activiti.engine.task.Task;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.transaction.annotation.Transactional;

import com.prs.core.workflow.dto.Document;
import com.prs.core.workflow.dto.TaskDTO;
import com.prs.core.workflow.service.WorkFlowEngine;

@Transactional(rollbackFor = Exception.class)
public class WorkFlowEngineImpl implements WorkFlowEngine {

	@Resource
	private HibernateTemplate hibernateTemplate;

	@Resource
	private ProcessEngine processEngin;

	/*
	 * 查询任务
	 */
	@SuppressWarnings("unchecked")
	@Override
	public List<TaskDTO> findMyTask(Map<String, Object> conditions) {

		Integer start = (Integer) conditions.get("start");
		Integer end = (Integer) conditions.get("end");
		String userId = (String) conditions.get("userId");
		List<TaskDTO> taskDTOList = new ArrayList<TaskDTO>();
		StringBuffer sql = new StringBuffer();
		sql.append("from Document where 1=1 ");

		TaskService taskService = this.processEngin.getTaskService();
		List<Task> list = taskService.createTaskQuery()
				.taskCandidateUser(userId).orderByTaskCreateTime().desc()
				.listPage(start, end);
		for (int i = 0; i < list.size(); i++) {
			Task task = list.get(0);
			sql.append("and PROCESS_INSTANCE_ID_ = '"
					+ task.getProcessInstanceId() + "'");
			final String typeSql = new String(sql);
			List<Document> documentList = (List<Document>) this.hibernateTemplate
					.find(typeSql);
			if (null != documentList && documentList.size() > 0) {
				TaskDTO taskDTO = new TaskDTO();
				Document document = documentList.get(0);
				taskDTO.setDocument(document);
				taskDTO.setTaskId(task.getId());
				taskDTOList.add(taskDTO);
			}

		}
		return taskDTOList;
	}

	/*
	 * 通过processKey启动流程
	 */
	@SuppressWarnings("unchecked")
	@Override
	public Document startProcessByKey(Map<String, Object> conditions) {
		RuntimeService runtimeService = this.processEngin.getRuntimeService();
		String key = (String) conditions.get("key");
		Document document = (Document)conditions.get("document");
		ProcessInstance processInstance = null;
		if (conditions.containsKey("values")) {
			Map<String, Object> values = (Map<String, Object>) conditions.get("key");
			processInstance = runtimeService.startProcessInstanceByKey(key,values);
		} else {
			processInstance = runtimeService.startProcessInstanceByKey(key);
		}
		if(null != processInstance){
			document.setProcessInstanceId(processInstance.getId());
			this.hibernateTemplate.save(document);
		}
		return document;
	}


	/* 
	 * 完成自己的任务
	 */
	@SuppressWarnings("unchecked")
	@Override
	public Document completeTask(Map<String, Object> conditions) {
		String taskId = (String)conditions.get("taskId");
		Document document = (Document)conditions.get("document");
		String userId = (String)conditions.get("userId");
		Map<String, Object> values = (Map<String, Object>) conditions.get("key");
		TaskService taskService = this.processEngin.getTaskService();
		//完成自己的任务
		taskService.claim(taskId, userId);
		taskService.complete(userId, values);
		//查询下一步经办人
		List<Task> taskList = taskService.createTaskQuery().processInstanceId(document.getProcessInstanceId()).list();
		String nowUser = findNowUser(taskList, taskService);
		if(null != nowUser && !"".equals(nowUser)){
			document.setNowUser(nowUser);
			this.hibernateTemplate.update(document);
		}
		return document;
	}
	
	//查询到当前经办的用户，如果存在授权的情况，则用授权人代替当前经办人
	private String findNowUser(List<Task> taskList,TaskService taskService){
		StringBuffer nowUser = new StringBuffer();
		for (Task task : taskList) {
			List<IdentityLink> ids = taskService.getIdentityLinksForTask(task.getId());
			for (IdentityLink identityLink : ids) {
				String userId = identityLink.getUserId();
				if(null != userId){
					
				}
			}
		}
		return nowUser.toString();
	}
	
}
